from django.conf import settings


def init_permission(user_obj, request):
    # 查询当前用户的权限信息
    permissions = user_obj.roles.filter(permissions__url__isnull=False).values(
        'permissions__url',
        'permissions__title',
        'permissions__is_menu',
        'permissions__icon',
    ).distinct()

    # 权限的列表
    permission_list = []
    # 菜单的列表
    menu_list = []

    for i in permissions:
        #  { permissions__url  permissions__title  }
        permission_list.append({'url': i['permissions__url']})

        if i.get('permissions__is_menu'):
            menu_list.append({
                'title': i['permissions__title'],
                'icon': i['permissions__icon'],
                'url': i['permissions__url'],
            })

    # 保存权限信息到session中
    request.session[settings.PERMISSION_SESSION_KEY] = permission_list

    # 保存菜单的信息
    request.session[settings.MENU_SESSION_KEY] = menu_list

    print(permission_list)
    print(menu_list)

    # 保存登陆状态
    request.session['is_login'] = True
